package com.education.api.controller.admin.education;

import com.education.business.service.education.*;
import com.education.business.service.system.ExamTaskService;
import com.education.common.utils.FileUtil;
import com.education.model.dto.TestPaperInfoStudentDto;
import com.education.model.subproject.ExamTask;
import jdk.nashorn.internal.objects.annotations.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.swing.filechooser.FileSystemView;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 上传下载
 */
@RestController
@RequestMapping("/exam")
public class UpDownloadController {
    @Autowired
    private UpDownLoadservice upDownLoadservice;
    public final static String UPLOAD_PATH_PREFIX = "static/ExamTaskZip/";
    public final static String UPLOAD_PATH_STUANSWER = "static/StudentQuestionAnswerZip/";
    /**
     * 单个文件上传
     * @param file
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/uploadSingle")
    public String uploadSingleFile(@RequestParam("fileUpName") MultipartFile file) {
        if (file.isEmpty()) {
            return "上传文件不能为空";
        }
        //获取文件名，带后缀
        String fileName = file.getOriginalFilename();
        /*如果限制文件上传类型例如：该接口限制只能上传图片，则增加图片格式校验*/
        List<String> imageType = Stream.of("7z","zip", "rar", "tar").collect(Collectors.toList());
        // 获取文件的后缀格式
        String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        if (!imageType.contains(fileSuffix)) return "非法文件";
        //加个UUID拼接，尽量避免文件名称重复
        String realPath = new String("education-api/src/main/resources/" + UPLOAD_PATH_PREFIX);
        String name = UUID.randomUUID().toString().replace("-","") + "_" + fileName;
        File dest = new File(realPath);
        //判断文件父目录是否存在
        if (!dest.getParentFile().exists())  dest.getParentFile().mkdir();
        //保存文件
        try {
            File newFile = new File(dest.getAbsolutePath() + File.separator + name);
            file.transferTo(newFile);
            //读取压缩后的json文件导入数据库
            String targetDir = upDownLoadservice.upLoadTask(dest.toString(),name);

        } catch (IOException e) {
            e.printStackTrace();
            return "上传文件异常";
        }
        FileUtil.delete(dest+name);
        return "";
    }
    /**
     * 文件下载
     * @param response
     * @return
     */
    @GetMapping("/downLoadExamTask")
    public void downLoadFile(HttpServletResponse response,@RequestParam("id")int examTaskId ) {
        String zipFile = upDownLoadservice.downLoadTaskById(response,examTaskId);
        //删除单个文件
        FileUtil.delete(zipFile);
    }
    /**
     * 答卷导出
     * @param response
     * @param studentInfos
     */
    @PostMapping("/downLoadStudentQuestionAnswer")
    public String downLoadStudentQuestionAnswer(HttpServletResponse response, @RequestBody List<TestPaperInfoStudentDto> studentInfos){
        String zipFile = upDownLoadservice.downLoadStudentQuestionAnswer(response,studentInfos);
        //删除单个文件
//        FileUtil.delete(zipFile);
        return zipFile;
    }

    @GetMapping("/downLoad")
    public String downLoadStudentAnswer(HttpServletResponse response){
        String path = "education-api"+File.separator+"src"+File.separator+"main"+File.separator+"resources"+File.separator+"static"+File.separator+"StudentQuestionAnswerZip"+File.separator+"考生答卷"+".zip";
        File file = new File(path);
        if (!file.exists()) return "文件不存在";
        try(
                InputStream inStream = new FileInputStream(file);
                OutputStream os = response.getOutputStream();
        ) {
            response.reset();
            response.setContentType("application/force-download");// 设置强制下载不打开
            //下载后的文件名
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("考生答卷.zip","UTF-8"));
            byte[] buff = new byte[1024];
            int len = -1;
            while ((len = inStream.read(buff)) > 0) {
                os.write(buff, 0, len);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
            return "下载文件异常";
        }
        return "";
    }

    /**
     * 答卷导入
     * @param file
     * @return
     */
    @PostMapping("/uploadStudentQuestionAnswer")
    public String upLoadStudentQuestionAnswer(@RequestParam("fileUpName") MultipartFile file){
        if (file.isEmpty()) {
            return "上传文件不能为空";
        }
        //获取文件名，带后缀
        String fileName = file.getOriginalFilename();
        /*如果限制文件上传类型例如：该接口限制只能上传图片，则增加图片格式校验*/
        List<String> imageType = Stream.of("7z","zip", "rar", "tar").collect(Collectors.toList());
        // 获取文件的后缀格式
        String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        if (!imageType.contains(fileSuffix)) return "非法文件";
        //加个UUID拼接，尽量避免文件名称重复
        String realPath = new String("education-api/src/main/resources/" + UPLOAD_PATH_STUANSWER);
        String name = UUID.randomUUID().toString().replace("-","") + "_" + fileName;
        File dest = new File(realPath);
        //判断文件父目录是否存在
        if (!dest.getParentFile().exists())  dest.getParentFile().mkdir();
        //保存文件
        try {
            File newFile = new File(dest.getAbsolutePath() + File.separator + name);
            file.transferTo(newFile);
            //读取压缩后的json文件导入数据库
            String targetDir = upDownLoadservice.upLoadStudentQuestionAnswer(dest.toString(),name);

        } catch (IOException e) {
            e.printStackTrace();
            return "上传文件异常";
        }
        return "";
    }


}
